<?php
session_start();

// 检查是否已安装
if (!file_exists(__DIR__ . '/../config/config.php')) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => '系统未安装']);
    exit;
}

require_once __DIR__ . '/../config/config.php';

// 检查用户是否已登录
if (!isset($_SESSION['user_logged_in']) || !$_SESSION['user_logged_in']) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => '用户未登录']);
    exit;
}

// 只接受POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => '只接受POST请求']);
    exit;
}

// 使用用户名而不是IP地址
$username = $_SESSION['username'] ?? '';
if (empty($username)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => '用户未正确登录']);
    exit;
}

$user_dir = __DIR__ . '/../users/' . $username;

// 确保用户目录存在
if (!file_exists($user_dir)) {
    mkdir($user_dir, 0755, true);
}

$message = $_POST['message'] ?? '';
$user_prompt = $_POST['user_prompt'] ?? 'You are a helpful assistant.';

if (empty($message)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => '消息不能为空']);
    exit;
}

// 读取历史聊天记录
$history_file = $user_dir . '/history.json';
$history = [];
if (file_exists($history_file)) {
    $history = json_decode(file_get_contents($history_file), true) ?: [];
}

// 添加用户消息到历史记录
$history[] = ['role' => 'user', 'content' => $message, 'timestamp' => date('Y-m-d H:i:s')];

// 准备API请求 - 修正API端点URL
$api_url = rtrim($config['base_url'], '/') . '/chat/completions';
$headers = [
    'Authorization: Bearer ' . $config['api_key'],
    'Content-Type: application/json'
];

// 准备消息数据，包含历史记录
$messages = [];
$messages[] = ['role' => 'system', 'content' => $user_prompt];
foreach ($history as $item) {
    $messages[] = ['role' => $item['role'], 'content' => $item['content']];
}

$data = [
    'model' => $config['default_model'],
    'messages' => $messages,
    'temperature' => 0.7
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 添加重定向支持
curl_setopt($ch, CURLOPT_MAXREDIRS, 3); // 限制重定向次数

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);

header('Content-Type: application/json');

if ($curl_error) {
    echo json_encode(['success' => false, 'error' => 'cURL错误: ' . $curl_error]);
} elseif ($http_code === 200) {
    $response_data = json_decode($response, true);
    if ($response_data && isset($response_data['choices'][0]['message']['content'])) {
        $ai_response = $response_data['choices'][0]['message']['content'];
        
        // 添加AI回复到历史记录
        $history[] = ['role' => 'assistant', 'content' => $ai_response, 'timestamp' => date('Y-m-d H:i:s')];
        
        // 保存更新后的历史记录
        file_put_contents($history_file, json_encode($history, JSON_PRETTY_PRINT));
        
        echo json_encode(['success' => true, 'response' => $ai_response]);
    } else {
        echo json_encode(['success' => false, 'error' => '无效的API响应格式: ' . $response]);
    }
} else {
    echo json_encode(['success' => false, 'error' => "API请求失败，HTTP状态码: $http_code, 响应: " . $response]);
}
?>
